#!/usr/bin/python3
from datetime import datetime
from datetime import timedelta
import pymysql
import sys
from util import datetime_to_string
from tushare_api import fetch_data_pro_bar

import tushare

print(tushare.__version__)

# C:\Users\zhu.chunfeng\Anaconda3\python.exe C:/Users/zhu.chunfeng/Desktop/finance/tushare/tushare_main.py
# 1.2.62

# 打开数据库连接
db = pymysql.connect(host="127.0.0.1", user="root", password="root", database="gupiao")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
sql = "select ts_code from stock_basic"
cursor.execute(sql)
fetchall = cursor.fetchall()
for stock_name in fetchall:
    tsCode = stock_name[0]
    basic = 'stock'
    freq = "30min"
    fromTime = datetime(2017, 1, 1)

    if basic == 'stock':
        sql = "select trade_time from pro_bar_stock  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    elif basic == 'index':
        sql = "select trade_time from pro_bar_index  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    elif basic == 'fund':
        sql = "select trade_time from pro_bar_fund  where ts_code ='" + tsCode + "' order by trade_time limit 1"
    else:
        raise Exception('basic 枚举有误!')
    print(sql)
    cursor.execute(sql)
    print(cursor.rowcount)
    nearlyTime = datetime(datetime.today().year, datetime.today().month, datetime.today().day)
    if cursor.rowcount > 0:
        nearlyTime = cursor.fetchone()[0]  # 2016-01-04 09:30:00
        nearlyTime = datetime(nearlyTime.year, nearlyTime.month, nearlyTime.day)
    print(nearlyTime)

    if fromTime >= nearlyTime:
        print("数据时间" + datetime_to_string(nearlyTime) + "小于设置时间" + datetime_to_string(fromTime))
        sys.exit(0)

    while fromTime < nearlyTime:
        timeDiff = timedelta(days=1000)
        timePre = nearlyTime - timeDiff
        if fromTime <= timePre:
            print(datetime_to_string(timePre) + '--->' + datetime_to_string(nearlyTime))
            fetch_data_pro_bar(tsCode, datetime_to_string(timePre), datetime_to_string(nearlyTime), basic,freq)
            nearlyTime = timePre
        else:
            timePre = fromTime
            print(datetime_to_string(timePre) + '----->' + datetime_to_string(nearlyTime))
            fetch_data_pro_bar(tsCode, datetime_to_string(timePre), datetime_to_string(nearlyTime), basic,freq)
            nearlyTime = timePre
# 关闭数据库连接
db.close()
